package com.example.demo.controller.train;

import cn.afterturn.easypoi.cache.manager.IFileLoader;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.base.config.auth.UserInfoShareHolder;
import com.example.demo.base.login.dto.UserCache;
import com.example.demo.common.QueryBaseParam;
import com.example.demo.domain.entity.TrainClass;
import com.example.demo.domain.entity.TrainClassHomework;
import com.example.demo.domain.entity.TrainClassUser;
import com.example.demo.domain.entity.TrainCommitRecord;
import com.example.demo.domain.entity.TrainHomework;
import com.example.demo.domain.entity.TrainHomeworkProblem;
import com.example.demo.domain.entity.User;
import com.example.demo.domain.vo.ClassUserSubmitInfoVo;
import com.example.demo.domain.vo.HomeWorkDetailVo;
import com.example.demo.domain.vo.TrainClassVo;
import com.example.demo.dto.ResponseDto;
import com.example.demo.enums.TrainSubmitStatus;
import com.example.demo.enums.UserIdentifyEnum;
import com.example.demo.param.TrainClassParam;
import com.example.demo.param.TrainClassUserParam;
import com.example.demo.service.TrainClassHomeworkService;
import com.example.demo.service.TrainClassService;
import com.example.demo.service.TrainClassUserService;
import com.example.demo.service.TrainCommitRecordService;
import com.example.demo.service.TrainHomeworkProblemService;
import com.example.demo.service.TrainHomeworkService;
import com.example.demo.service.UserService;
import com.example.demo.utils.BeanCopyUtil;
import com.example.demo.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 培训模块-用户相关
 * @author liguang03
 * @date 2024/2/2
 */
@Controller
@Slf4j
@RequestMapping("/train/train-user")
public class UserTrainController {

    @Resource
    private TrainClassService trainClassService;

    @Resource
    private TrainClassUserService trainClassUserService;

    @Resource
    private TrainClassHomeworkService trainClassHomeworkService;


    @Resource
    private TrainHomeworkService trainHomeworkService;


    @Resource
    private UserService userService;


    @Resource
    private TrainHomeworkProblemService trainHomeworkProblemService;



    @Resource
    private TrainCommitRecordService trainCommitRecordService;


    /**
     * 加入班级-邀请码
     * @param
     * @return
     */
    @RequestMapping("/user/add/class/")
    @ResponseBody
    public ResponseDto<Boolean> userAddTrainClass(@NotBlank String inviteCode){
        UserCache userInfo = UserInfoShareHolder.getUserInfo();
        if (userInfo.getUser() == null) {
            return new ResponseDto<Boolean>().buildFail("未登录");
        }
        TrainClass trainClass = trainClassService.queryByInviteCode(inviteCode);
        if (trainClass == null) {
            return new ResponseDto<Boolean>().buildFail("未查询到对应的班级");
        }
        if (!userService.isIdentity(userInfo.getUser().getId())){
            return new ResponseDto<>().buildFail("请先实名认证，再加入班级");
        }
        TrainClassUser trainClassUser1 = trainClassUserService.queryByUserAndClass(trainClass.getId(), userInfo.getUser().getId());
        if (trainClassUser1 != null) {
            return new ResponseDto<>().buildFail("您已经再该班级中，无需重新申请");
        }
        TrainClassUser trainClassUser = new TrainClassUser();
        trainClassUser.setClassId(trainClass.getId());
        trainClassUser.setRealName(userInfo.getUser().getRealName());
        trainClassUser.setUserId(userInfo.getUser().getId());
        boolean save = trainClassUserService.save(trainClassUser);
        return new ResponseDto<Boolean>().buildSucceedHasData(save);
    }


    /**
     * 获取用户所在的班级
     * @param queryBaseParam
     * @return
     */
    @RequestMapping("/user/class/")
    @ResponseBody
    public ResponseDto<Page<TrainClassVo>> getUserClass(@RequestBody QueryBaseParam queryBaseParam) {
        UserCache userInfo = UserInfoShareHolder.getUserInfo();
        List<TrainClassUser> trainClassUsers = trainClassUserService.getByUserId(userInfo.getUser().getId());
        if (CollectionUtils.isEmpty(trainClassUsers)){
            return new ResponseDto().buildSucceed();
        }
        List<Long> classIds = trainClassUsers.stream().map(TrainClassUser::getClassId).collect(Collectors.toList());
        Page<TrainClass> result = trainClassService.getByIdsAndPage(classIds, queryBaseParam);
        List<TrainClass> records = result.getRecords();
        if (CollectionUtils.isEmpty(records)){
            return new ResponseDto().buildSucceed();
        }
        List<TrainClassVo> trainClassVos = BeanCopyUtil.copyListProperties(records, TrainClassVo::new);
        List<Long> collect = trainClassVos.stream().map(TrainClassVo::getBelongTeacherId).collect(Collectors.toList());
        Map<Long, User> longUserMap = userService.queryByIds(collect);
        for (TrainClassVo trainClassVo : trainClassVos) {
            User user = longUserMap.get(trainClassVo.getBelongTeacherId());
            trainClassVo.setTeacherName(user!= null ? user.getRealName() : "");
        }
        Page<TrainClassVo> page = new Page<>();
        BeanUtils.copyProperties(result, page);
        page.setRecords(trainClassVos);
        return new ResponseDto().buildSucceedHasData(page);
    }





    /**
     * 分页获取某一个班级的作业
     * @param trainClassUserParam
     * @return
     */
    @RequestMapping("/user/class/homework")
    @ResponseBody
    public ResponseDto<Page<HomeWorkDetailVo>> getUserClassHomework(@RequestBody TrainClassUserParam trainClassUserParam) {
        UserCache userInfo = UserInfoShareHolder.getUserInfo();
        //判断该学生是否在这个班级，或者管理者的相关权限
        Long trainClassId = trainClassUserParam.getTrainClassId();
        TrainClass trainClass = trainClassService.getById(trainClassId);
        if (trainClass == null){
            return new ResponseDto<>().buildFail("错误参数");
        }
        if (UserIdentifyEnum.companyUser.getIdentify().equals(userInfo.getUser().getIdentify())
         || UserIdentifyEnum.companyAdmin.getIdentify().equals(userInfo.getUser().getIdentify())){
            if (!trainClass.getCompanyId().equals(userInfo.getCompanyId())){
                return new ResponseDto<>().buildFail("无权限操作");
            }
        }

        if (UserIdentifyEnum.normalUser.getIdentify().equals(userInfo.getUser().getIdentify())){
            TrainClassUser user = trainClassUserService.queryByUserAndClass(trainClassId, userInfo.getUser().getId());
            if (user == null) {
                return new ResponseDto<>().buildFail("无权限查看");
            }
        }

        Page<TrainHomework> trainHomeworkPage = trainHomeworkService.queryHomeWork(trainClassUserParam);
        if (CollectionUtils.isEmpty(trainHomeworkPage.getRecords())){
            return new ResponseDto().buildSucceed();
        }
        List<TrainHomework> records = trainHomeworkPage.getRecords();
        List<Long> homeworkIds = records.stream().map(TrainHomework::getId).collect(Collectors.toList());
        List<TrainHomeworkProblem> trainHomeworkProblems = trainHomeworkProblemService.queryByHwIds(homeworkIds);

        //获取提交记录
        Page<HomeWorkDetailVo> result = new Page<>();
        result.setTotal(trainHomeworkPage.getTotal());
        result.setCurrent(trainHomeworkPage.getCurrent());
        result.setSize(trainHomeworkPage.getSize());
        if (CollectionUtils.isEmpty(trainHomeworkPage.getRecords())){
            return new ResponseDto().buildSucceedHasData(result);
        }
        List<HomeWorkDetailVo> homeWorkDetailVos = BeanCopyUtil.copyListProperties(trainHomeworkPage.getRecords(), HomeWorkDetailVo::new);
        Map<Long, TrainHomeworkProblem> map = trainHomeworkProblems.stream().collect(Collectors.toMap(TrainHomeworkProblem::getHomeworkId, o -> o, (a, b) -> b));
        result.setRecords(homeWorkDetailVos);
        for (HomeWorkDetailVo homeWorkDetailVo : homeWorkDetailVos) {
            Long homeWorkId = homeWorkDetailVo.getId();
            TrainHomeworkProblem trainHomeworkProblem = map.get(homeWorkId);
            if (trainHomeworkProblem == null){
                continue;
            }
            List<TrainCommitRecord> trainCommitRecords = trainCommitRecordService.queryByHwIdAndPIdAndClassIdAndUser(homeWorkId, trainHomeworkProblem.getProblemId(), trainClassId, userInfo.getUser().getId());

            trainCommitRecords = trainCommitRecords.stream().filter(trainCommitRecord -> CommonUtil.isNotNullId(trainCommitRecord.getSubmitId())).collect(Collectors.toList());
            trainCommitRecords.sort(Comparator.comparing(TrainCommitRecord::getSubmitTime, Comparator.reverseOrder()));
            int size = trainCommitRecords.size();
            if (CollectionUtils.isNotEmpty(trainCommitRecords)){
                TrainCommitRecord record = trainCommitRecords.get(0);
                homeWorkDetailVo.setLastSubmitId(record.getSubmitId());
                homeWorkDetailVo.setSubmitStatus(record.getSubmitTime() == null ? TrainSubmitStatus.NOT_SUBMIT.getKey() : TrainSubmitStatus.SUBMIT.getKey());
                homeWorkDetailVo.setScore(record.getScore());
                homeWorkDetailVo.setSubmitTimes(size);
                homeWorkDetailVo.setSubmitTime(record.getSubmitTime());
            }else {
                homeWorkDetailVo.setSubmitStatus(TrainSubmitStatus.NOT_SUBMIT.getKey() );
                homeWorkDetailVo.setSubmitTimes(size);
            }
        }
        return new ResponseDto().buildSucceedHasData(result);
    }



    /*public ResponseDto<String> judgeBaseCheck(){
        UserCache userInfo = UserInfoShareHolder.getUserInfo();

    }*/



    /**
     * 分页获取某一个作业提交情况
     * @param trainClassUserParam
     * @return
     */
    @RequestMapping("/user/homework/submit-detail")
    @ResponseBody
    public ResponseDto<Page<ClassUserSubmitInfoVo>> getSubmitDetail(@RequestBody TrainClassUserParam trainClassUserParam) {
        UserCache userInfo = UserInfoShareHolder.getUserInfo();
        //判断相关权限
        Long trainClassId = trainClassUserParam.getTrainClassId();
        TrainClass trainClass = trainClassService.getById(trainClassId);
        if (trainClass == null){
            return new ResponseDto<>().buildFail("错误参数");
        }
        if (UserIdentifyEnum.companyUser.getIdentify().equals(userInfo.getUser().getIdentify())
                || UserIdentifyEnum.companyAdmin.getIdentify().equals(userInfo.getUser().getIdentify())){
            if (!trainClass.getCompanyId().equals(userInfo.getCompanyId())){
                return new ResponseDto<>().buildFail("无权限操作");
            }
        }
        Page<ClassUserSubmitInfoVo> result = trainClassUserService.getSubmitDetail(trainClassUserParam);

        return new ResponseDto().buildSucceedHasData(result);
    }















}
